package com.kits.store.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.DocumentsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kits.store.R
import com.kits.store.utils.SpStoreUtils
import kotlinx.android.synthetic.main.fragment_saf.*
import me.yokeyword.fragmentation.ISupportFragment
import me.yokeyword.fragmentation.SupportFragment
import java.text.SimpleDateFormat
import java.util.*


/**
 * 使用SAF 访问 SD 卡文件
 * 注意点
 * 1. 使用 SAF 打开的路径是 最近一次 打开的路径。
 * 2. 如何是打开文件，如何获取多个文件的Uri?
 *
 */
class SAFfragment : SupportFragment(){

    companion object{
        /**
         * 打开单一文件，并读取内容
         */
        const val REQUEST_SINGLE_READ_FILE = 100

        /**
         * 打开多个文件
         */
        const val REQUEST_MULTI_FILE = 101

        /**
         * 删除文件
         */
        const val REQUEST_DELETE_FILE = 102

        /**
         *  创建文件
         */
        const val REQUEST_CREATE_FILE = 103

        /**
         * 修改文件内容
         */
        const val REQUEST_ALTER_FILE = 104

        /**
         * 重命名文件
         */

        const val REQUEST_RENAME_FILE = 105

        /**
         * 打开文件夹
         */

        const val REQUEST_OPEN_DOCUMENT_TREE = 106

        fun newInstance() :SAFfragment{
            val args = Bundle()
            val fragment = SAFfragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_saf,container,false)
    }

    override fun onResume() {
        super.onResume()
        initView()
    }

    private fun initView(){
        btnOpenSingle.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false)
            }
            startActivityForResult(intent, REQUEST_SINGLE_READ_FILE)
        }

        btnOpenMulti.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE,true)
            }
            startActivityForResult(intent, REQUEST_MULTI_FILE)
        }

        btnDeleteFile.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false)
            }
            startActivityForResult(intent, REQUEST_DELETE_FILE)
        }

        btnCreateFile.setOnClickListener {
            // 读取sp 文件 first
            val uri = SpStoreUtils.getParam<String>("first")
            if (!uri.isNullOrBlank()){
                val fileUri = Uri.parse(uri)
                // 文件不存在会抛出异常 注意处理一下
                context?.contentResolver?.takePersistableUriPermission(fileUri,Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                // 写入文件看一下喽
                val outputStream = context?.contentResolver?.openOutputStream(fileUri)
                outputStream?.write("我就是简单的常识一下，写入文件，看看是否成功\n".toByteArray())
                outputStream?.close()
            }else{
                val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    // 文件类型
                    type="text/plain"
                    // 文件名称
                    val filename: String = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA).format(
                        Date()
                    ).toString() + ".txt"
                    putExtra(Intent.EXTRA_TITLE, filename)
                }
                startActivityForResult(intent, REQUEST_CREATE_FILE);
            }

        }

        btnAlterFile.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false)
            }
            startActivityForResult(intent, REQUEST_ALTER_FILE)
        }
        btnRenameFile.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                addCategory(Intent.CATEGORY_OPENABLE)
                type = "text/*"
                putExtra(Intent.EXTRA_ALLOW_MULTIPLE,false)
            }
            startActivityForResult(intent, REQUEST_RENAME_FILE)
        }

        btnSpTest.setOnClickListener {
            SpStoreUtils.setParam("aa",100)
            println("aa = ${SpStoreUtils.getParam<Int>("aa")}")

            SpStoreUtils.setParam("bb",100.0f)
            println("bb = ${SpStoreUtils.getParam<Float>("bb")}")

            SpStoreUtils.setParam("cc",100.9)
            println("cc = ${SpStoreUtils.getParam<Double>("cc")}")

            SpStoreUtils.setParam("dd","123")
            println("dd = ${SpStoreUtils.getParam<String>("dd")}")

            SpStoreUtils.setParam("ee",true)
            println("ee = ${SpStoreUtils.getParam<Boolean>("ee")}")

            SpStoreUtils.setParam("ff",10000L)
            println("ff = ${SpStoreUtils.getParam<Long>("ff")}")
        }


        btnDirTree.setOnClickListener {
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
            startActivityForResult(intent, REQUEST_OPEN_DOCUMENT_TREE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        println("requestCode == $requestCode;resultCode == $resultCode")
        if(resultCode == ISupportFragment.RESULT_OK){
            when(requestCode){
                REQUEST_SINGLE_READ_FILE ->{

                    val fileUri = data?.data
                    println("fileUri === $fileUri")
                    println("路径 === ${fileUri?.path}")
                    fileUri?.let {
                        // 读取内容
                        println("读文件内容==")
                        readFileUri(it)
                        println("写文件内容==")
                        writeFileUri(fileUri)
                    }
                    return
                }
                REQUEST_MULTI_FILE->{
                    println("multi ========== ,通过截切板来获取数据")
                    val clipData = data?.clipData
                    clipData?.let {
                        for (i in 0 until clipData.itemCount){
                            val selectUri = clipData.getItemAt(i).uri
                            println("选择的uri === $selectUri")
                            // 读取一下内容
                            val inputStream = context?.contentResolver?.openInputStream(selectUri)
                            val buf = ByteArray(inputStream!!.available())
                            inputStream.read(buf)
                            println("buf == ${String(buf)}")
                        }
                    }
                    return
                }

                REQUEST_DELETE_FILE->{
                    val fileUri = data?.data
                    println("fileUri === $fileUri")
                    fileUri?.let {
                        DocumentsContract.deleteDocument(context?.contentResolver!!,it)
                    }
                }
                REQUEST_CREATE_FILE->{
                    println("===创建文件 == ")
                    val fileUri = data?.data
                    // 写入文件
                    fileUri?.let {
                        val outputStream = context?.contentResolver?.openOutputStream(fileUri)
                        outputStream?.write("写入一行文字,尝试一下喽\n".toByteArray())
                        outputStream?.close()
                        // 申请写的权限
                        context?.contentResolver?.takePersistableUriPermission(fileUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                        // 申请成功，写入sp文件
                        SpStoreUtils.setParam("first",fileUri.toString())

                    }

                }

                // 修改文件内容
                REQUEST_ALTER_FILE->{
                    println("修改文件内容==")
                    val fileUri = data?.data
                    println("fileUri === $fileUri")
                    fileUri?.let {

                        val outputStream = requireContext().contentResolver?.openOutputStream(fileUri)
                        outputStream?.let {
                            outputStream.write("这是更新的内容\n".toByteArray())
                            outputStream.close()
                        }

                    }

                }

                REQUEST_RENAME_FILE->{
                    println("文件重命名====")
                    val fileUri = data?.data
                    println("fileUri === $fileUri")
                    fileUri?.let {
                        DocumentsContract.renameDocument(context?.contentResolver!!,it,"myTest.txt")
                    }
                }
                // 非常类似PC上面设置保存路径
                REQUEST_OPEN_DOCUMENT_TREE->{
                    println("打开文件夹")
                    var fileUri = data?.data
                    println("fileUri == $fileUri")

                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }


    private fun readFileUri(fileUri:Uri){
        val inputStream = context?.contentResolver?.openInputStream(fileUri)
        val buf = ByteArray(inputStream!!.available())
        inputStream.read(buf)
        println("buf == ${String(buf)}")
    }

    private fun writeFileUri(fileUri:Uri){
        val outputStream = requireContext().contentResolver?.openOutputStream(fileUri)
        outputStream?.let {

            outputStream.write("这是更新的内容==writeFileUri\n".toByteArray())
            outputStream.close()
        }
    }
}